from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

ava_event_project_api = Blueprint('ava_event_project_api', __name__)
ava_event_project_down_api = Blueprint('ava_event_project_down_api', __name__)
ava_event_project_sync_api = Blueprint('ava_event_project_sync_api', __name__)
ava_event_project_sync_preprocessing_api = Blueprint('ava_event_project_sync_preprocessing_api', __name__)

@ava_event_project_api.route('/ava_event_project', methods=['POST'])
def ava_event_project():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        query = AvaEventProject.query.order_by('project').all()
        result = []
        for q in query:
            localization = json.loads(q.localization)
            if "1" in localization:
                title = localization["1"]["title"]
            else:
                title = ''
            tmp = {
                "project": int(q.project),
                'title': title,
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        query = AvaEventProject.query.filter_by(project=_project).first()
        event_calendar = json.loads(query.event_calendar)

        reward = json.loads(query.reward)
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'defeat_alliance_goal_reward': reward["defeat"]["alliance_goal_reward"],
            'defeat_result_reward': reward["defeat"]["result_reward"],
            'defeat_user_goal_reward': reward["defeat"]["user_goal_reward"],
            'victory_alliance_goal_reward': reward["victory"]["alliance_goal_reward"],
            'victory_result_reward': reward["victory"]["result_reward"],
            'victory_user_goal_reward': reward["victory"]["user_goal_reward"],
            'match_fail_reward': reward["match_fail_reward"],
            'user_rank_reward': reward["user_rank_reward"],
            'event_calendar': event_calendar
        }
        result_data['data']['item'] = tmp

    elif _action == 'doc_id_list':
        doc_file_data = GetDocByFilename('ava_event')
        result = []
        for k, v in doc_file_data.items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
        return json.dumps(result)

    elif _action == 'remark':
        newRemark = params['remark']
        AvaEventProject.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        ava_data = AvaEventProject.query.filter_by(project=_project).first()
        reward = json.loads(ava_data.reward)
        if _part == 'basic':
            AvaEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'calendar':
            AvaEventProject.query.filter_by(project=_project).update({
                'event_calendar': json.dumps(_data)
            })
        elif _part == 'defeat_alliance_goal_reward':
            reward["defeat"]["alliance_goal_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'defeat_result_reward':
            reward["defeat"]["result_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'defeat_user_goal_reward':
            reward["defeat"]["user_goal_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'victory_alliance_goal_reward':
            reward["victory"]["alliance_goal_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'victory_result_reward':
            reward["victory"]["result_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'victory_user_goal_reward':
            reward["victory"]["user_goal_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'match_fail_reward':
            reward["match_fail_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'user_rank_reward':
            reward["user_rank_reward"] = _data
            AvaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'clone':  # 克隆方案
        ava_event_project_data = AvaEventProject.query.filter_by(project=_project).first()
        new_project_data = AvaEventProject(
            basic=ava_event_project_data.basic,
            localization=ava_event_project_data.localization,
            reward=ava_event_project_data.reward,
            event_calendar=ava_event_project_data.event_calendar,
            remark = ava_event_project_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        ava_event_project_data = AvaEventProject.query.filter_by(project=_project).first()
        db.session.delete(ava_event_project_data)
        db.session.commit()
        ava_event_project_data = AvaEventProject.query.filter_by(project=_project).first()
        if ava_event_project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    return jsonify(result_data)


@ava_event_project_down_api.route('/ava_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def ava_event_project_down(is_push):
    def get_reward_info(r):
        t = {"a": [r['type'], r['id'], r['num']]}
        return t
    def get_reward_list(a):
        tmp_reward = []
        for i in range(0, len(a)):
            for j in range(0, len(a[i]['reward'])):
                tmp_reward.append(get_reward_info(a[i]['reward'][j]))
        return tmp_reward

    result = {}

    query = AvaEventProject.query.order_by('project').all()
    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        localization = json.loads(q.localization)
        reward_data = json.loads(q.reward)
        event_calendar = json.loads(q.event_calendar)
        calc_score = {
            "alliance_add_score_type": [46],
            "user_add_score_type": [47],
            "user_score_type_list": [
                {
                    "doc": {
                        "1": "Kill 150 Troop Force",
                        "2": "Kill 150 Troop Force",
                        "3": "Kill 150 Troop Force",
                        "5": "Kill 150 Troop Force",
                        "6": "Kill 150 Troop Force",
                        "7": "消灭150单位军队力量",
                        "8": "Kill 150 Troop Force",
                        "9": "Kill 150 Troop Force",
                        "10": "Kill 150 Troop Force",
                        "11": "Kill 150 Troop Force",
                        "12": "Kill 150 Troop Force",
                        "13": "Kill 150 Troop Force",
                        "14": "Kill 150 Troop Force",
                        "15": "Kill 150 Troop Force",
                        "16": "Kill 150 Troop Force",
                        "17": "Kill 150 Troop Force",
                        "18": "Kill 150 Troop Force",
                        "19": "Kill 150 Troop Force",
                        "20": "Kill 150 Troop Force",
                        "21": "Kill 150 Troop Force"
                    },
                    "points": 1,
                    "rule_list": [
                        {
                            "factor": 67,
                            "score_id_map": {
                                "-1": 0
                            }
                        }
                    ],
                    "score_type": 1
                }
            ]
        }

        if 'remark' in basic:
            del basic['remark']

        for i in localization:
            if 'calendar_info' in localization[i]:
                del localization[i]['calendar_info']
            if 'calendar_title' in localization[i]:
                del localization[i]['calendar_title']

        reward_data['match_fail_reward'] = get_reward_list(reward_data['match_fail_reward'])

        for i in range(0, len(reward_data['user_rank_reward'])):
            reward_data['user_rank_reward'][i]['reward'] = RewardToTMysqlNew(reward_data['user_rank_reward'][i]['reward'])

        for i in range(0, len(reward_data['victory']['alliance_goal_reward'])):
            reward_data['victory']['alliance_goal_reward'][i]['reward'] = RewardToTMysqlNew(reward_data['victory']['alliance_goal_reward'][i]['reward'])

        reward_data['victory']['result_reward'] = get_reward_list(reward_data['victory']['result_reward'])

        for i in range(0, len(reward_data['victory']['user_goal_reward'])):
            reward_data['victory']['user_goal_reward'][i]['reward'] = RewardToTMysqlNew(reward_data['victory']['user_goal_reward'][i]['reward'])

        for i in range(0, len(reward_data['defeat']['alliance_goal_reward'])):
            reward_data['defeat']['alliance_goal_reward'][i]['reward'] = RewardToTMysqlNew(reward_data['defeat']['alliance_goal_reward'][i]['reward'])

        reward_data['defeat']['result_reward'] = get_reward_list(reward_data['defeat']['result_reward'])

        for i in range(0, len(reward_data['defeat']['user_goal_reward'])):
            reward_data['defeat']['user_goal_reward'][i]['reward'] = RewardToTMysqlNew(reward_data['defeat']['user_goal_reward'][i]['reward'])

        event_calendar['reward'] = RewardToTMysqlNew(event_calendar['reward'])

        if 'calendar_doc_id' in event_calendar:
            _calendar_doc_id = event_calendar['calendar_doc_id']
        else:
            _calendar_doc_id = 1

        if '_tag' in basic:
            _tag = basic['_tag']
            del basic['_tag']
        else:
            _tag = []

        tmp = {
            '_tag': _tag,
            "basic": basic,
            "calc_score": calc_score,
            "localization": localization,
            "reward": reward_data,
            "calendar_conf": {
                'event_type': 14,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': _calendar_doc_id,
                    'info': _calendar_doc_id
                },
                'reward': event_calendar['reward'],
                'show_type': 0
            }
        }
        result[_project] = tmp

    response = DownLoad('ava_event_project', result, is_push)

    return response


@ava_event_project_sync_api.route('/ava_event_project_sync/', methods=['GET', 'POST'])
def ava_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], reward_list)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/ava_event_project_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i)
        _basic = data[i]['basic']
        _localization = data[i]['localization']
        _remark = str(_project)
        if "1" in _localization:
            if "title" in _localization["1"]:
                _remark = _localization["1"]["title"]
        _reward = {
            "defeat": {
                "alliance_goal_reward": [],
                "result_reward": [],
                "user_goal_reward": []
            },
            "match_fail_reward": [],
            "user_rank_reward": [],
            "victory": {
                "alliance_goal_reward": [],
                "result_reward": [],
                "user_goal_reward": []
            }
        }
        for j in data[i]['reward']['defeat']['alliance_goal_reward']:
            _reward['defeat']['alliance_goal_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'target': j['target']})
        _reward['defeat']['result_reward'].append({"reward": RewardShowToDocBonus3(data[i]['reward']['defeat']['result_reward'], reward_list)})
        for j in data[i]['reward']['defeat']['user_goal_reward']:
            _reward['defeat']['user_goal_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'target': j['target']})
        for j in data[i]['reward']['victory']['alliance_goal_reward']:
            _reward['victory']['alliance_goal_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'target': j['target']})
        _reward['victory']['result_reward'].append({"reward": RewardShowToDocBonus3(data[i]['reward']['victory']['result_reward'], reward_list)})
        for j in data[i]['reward']['victory']['user_goal_reward']:
            _reward['victory']['user_goal_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'target': j['target']})
        _reward['match_fail_reward'].append({"reward": RewardShowToDocBonus3(data[i]['reward']['match_fail_reward'], reward_list)})
        for j in data[i]['reward']['user_rank_reward']:
            _reward['user_rank_reward'].append({"reward": RewardShowToDocBonus3(j['reward'], reward_list), 'from': j['from'], 'to': j['to']})
        if len(_reward['victory']['user_goal_reward']) > 0:
            _maxGoal = _reward['victory']['user_goal_reward'][0]['target']
            _maxReward = _reward['victory']['user_goal_reward'][0]['reward']
        else:
            _maxGoal = [],
            _maxReward = -1
        for j in _reward['victory']['user_goal_reward']:
            if j['target'] > _maxGoal:
                _maxGoal = j['target']
                _maxReward = j['reward']

        _event_calendar = {
            "event_ui": 12,
            "jump": 1,
            "order": 1,
            "show_type": 0,
            "title": '',
            'reward': _maxReward,
            'localization': ''
        }
        new_project_data = AvaEventProject(
            project=_project,
            basic=json.dumps(_basic),
            localization=json.dumps(_localization),
            reward=json.dumps(_reward),
            event_calendar=json.dumps(_event_calendar),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})

@ava_event_project_sync_preprocessing_api.route('/ava_event_project_sync/preprocessing', methods=['GET', 'POST'])
def ava_event_project_sync_preprocessing():
    with open(STATIC_PATH + '../sync/ava_event_project.json', encoding='utf8') as f:
        data = json.load(f)
    with open(STATIC_PATH + '../sync/ava_event_project_preprocessing.json', 'w', encoding='utf8') as f:
        f.write(json.dumps(data, sort_keys=True))

    return jsonify({'msg': 'finished'})
